package com.onenine.app.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.just.agentweb.AgentWeb;
import com.onenine.app.R;
import com.onenine.app.application.NineteenApp;
import com.onenine.app.event.FloatGameEvent;
import com.onenine.app.event.GameChatEvent;
import com.onenine.app.event.PaySuccessEvent;
import com.onenine.app.model.GameCmdMsg;
import com.onenine.app.model.GameTargetJoin;
import com.onenine.app.model.GameUserInfo;
import com.onenine.app.response.ConvertUidResponse;
import com.onenine.app.service.MessageQueueService;
import com.onenine.app.utils.CDataProcessor;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.base.base.BaseEventActivity;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.utils.AnimHelper;
import com.onenine.base.utils.StatusBarUtils;
import com.onenine.base.utils.Toasty;
import com.onenine.chat.rongcloud.RcImMgr;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.Logger;
import com.onenine.common.util.SizeUtils;
import com.onenine.common.util.SoftKeyboardListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;

/**
 * 文字游戏进行中
 */
public class GameRunningTextActivity extends BaseEventActivity
        implements View.OnClickListener, SoftKeyboardListener.OnSoftKeyBoardChangeListener {

    public static final String GAME_TAG = "game_tag";//用于标识游戏聊天或音视频tag
    private static final String FUNCTION_SEND_MSG = "postMessageToGame";
    private static final String CMD_TARGET_JOIN = "targetJoin";
    private static final String CMD_TARGET_LEAVE = "targetLeave";
    private static final String CMD_USER_DETAIL = "launchUserDetail";
    private static final String CMD_RECHARGE = "charge";
    private static final String CMD_EXIT = "exit";
    private final String ANDROID_OBJECT_NAME = "client";
    private FrameLayout mWebLayout;
    private AgentWeb mAgentWeb;
    private EditText mEdtMsg;
    private TextView mTvTitle, mBtnAction;
    private TextView mTxtSend, mTxtReceive;
    private View mChatBar;
    protected GameTargetJoin mGameTargetJoin;
    private boolean isSending;

    public interface OnUid2UserIdResult {
        void onConvert(String userId);
    }

    public static void launchActivity(Context context, String gameUrl
            , String roomId, String uid) {
        Intent intent = new Intent(context, GameRunningTextActivity.class);
        intent.putExtra("gameUrl", gameUrl);
        intent.putExtra("roomId", roomId);
        intent.putExtra("uid", uid);
        context.startActivity(intent);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_game_running_text;
    }

    @Override
    protected void setStatusBarStyle() {
    }

    @Override
    protected void initViews() {
        super.initViews();
        StatusBarUtils.setTransparentForImageView(this, null);
        mTvTitle = findViewById(R.id.tv_title);
        mWebLayout = findViewById(R.id.fl_web_view);
        mBtnAction = findViewById(R.id.btn_send);
        mEdtMsg = findViewById(R.id.edt_content);
        mChatBar = findViewById(R.id.ll_chat_bar);
        mTxtSend = findViewById(R.id.tv_send_txt);
        mTxtReceive = findViewById(R.id.tv_receive_txt);
        setChatBottomMargin(getResources()
                .getDimensionPixelOffset(R.dimen.game_chat_bar_bottom_margin));
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        mBtnAction.setOnClickListener(this);
        SoftKeyboardListener.setListener(this, this);
        findViewById(R.id.btn_back).setOnClickListener(this);
        findViewById(R.id.btn_quit).setOnClickListener(this);
    }

    @Override
    protected void initData() {
        super.initData();
        Intent intent = getIntent();
        if (useIndicatorEnable()) {
            mAgentWeb = AgentWeb.with(this)
                    .setAgentWebParent(mWebLayout, new FrameLayout.LayoutParams(FrameLayout
                            .LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
                    .useDefaultIndicator(RoleResLoader.getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR))
                    .createAgentWeb().ready()
                    .go(getWebUrl(intent));
        } else {
            mAgentWeb = AgentWeb.with(this)
                    .setAgentWebParent(mWebLayout, new FrameLayout.LayoutParams(FrameLayout
                            .LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
                    .closeIndicator()
                    .createAgentWeb().ready()
                    .go(getWebUrl(intent));
        }
        mAgentWeb.getJsInterfaceHolder().addJavaObject(ANDROID_OBJECT_NAME, this);
        mAgentWeb.getWebCreator().getWebView().setBackgroundColor(Color.BLACK);
    }

    /**
     * 生成游戏web链接
     *
     * @param intent
     * @return
     */
    protected String getWebUrl(Intent intent) {
        String gameRunningUrl = String.format("%s?roomId=%s&uid=%s&scene=big"
                , intent.getStringExtra("gameUrl"), intent.getStringExtra("roomId")
                , intent.getStringExtra("uid"));
        Logger.e("游戏正在进行中：" + gameRunningUrl);
        return gameRunningUrl;
    }

    /**
     * 调用Js函数
     *
     * @param jsName
     */
    private void callJSFunction(String jsName, String... contents) {
        mAgentWeb.getJsAccessEntrace().quickCallJs(jsName, contents);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().post(new FloatGameEvent(getClass(), true));
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_back) {
            //移至后台，缩为小窗口
            moveTaskToBack(true);
        } else if (v.getId() == R.id.btn_quit) {
            //关闭
            finish();
        } else if (v.getId() == R.id.btn_send) {
            //聊天或发送
            if (isSending) {
                String msg = mEdtMsg.getText()
                        .toString().trim();
                if (msg.length() > 0) {
                    postMessageToTarget(msg);
                    mEdtMsg.setText("");
                } else {
                    isSending = false;
                    mBtnAction.setText(R.string.chat);
                    mEdtMsg.setVisibility(View.GONE);
                }
            } else {
                isSending = true;
                mBtnAction.setText(R.string.send);
                mEdtMsg.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 向对方发送文本消息
     *
     * @param msg
     */
    private void postMessageToTarget(String msg) {
        if (mGameTargetJoin == null) {
            return;
        }
        if (TextUtils.isEmpty(mGameTargetJoin.getUserId())) {
            CDataProcessor.convertUserPkId2UserId(mGameTargetJoin.getUid(), new OkCallback<ConvertUidResponse>() {
                @Override
                public void onResponse(ConvertUidResponse response, String srcData) {
                    if (response.isSuccess()) {
                        sendGameTextMessage(response.getObjId(), msg);
                        mGameTargetJoin.setUserId(response.getObjId());
                    }
                }
            });
        } else {
            sendGameTextMessage(mGameTargetJoin.getUserId(), msg);
        }
    }

    /**
     * 发送RC消息
     *
     * @param userId
     * @param msg
     */
    private void sendGameTextMessage(String userId, String msg) {
        RcImMgr.getInstance().sendGameTextMessage(Conversation.ConversationType.PRIVATE, userId
                , msg, new RcImMgr.OnMessageListener() {
                    @Override
                    public void onSuccess(Message message) {
                        MessageQueueService.beginMessageService(ApUtils.getApp()
                                , new GameChatEvent(true, msg));
                    }

                    @Override
                    public void onProgress(Message message) {

                    }

                    @Override
                    public void onFailure(RongIMClient.ErrorCode errorCode) {

                    }
                });
    }

    @Override
    public void onBackPressed() {
        //移至后台，缩为小窗口
        moveTaskToBack(true);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        EventBus.getDefault().post(new FloatGameEvent(getClass(), false));
    }

    @Override
    public void keyBoardShow(int height) {
        setChatBottomMargin(height + SizeUtils.dp2px(20));
    }

    @Override
    public void keyBoardHide(int height) {
        setChatBottomMargin(getResources().getDimensionPixelOffset(R.dimen.game_chat_bar_bottom_margin));
    }

    /**
     * 设置聊天底部边距
     *
     * @param bottomMargin
     */
    private void setChatBottomMargin(int bottomMargin) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mChatBar.getLayoutParams();
        lp.setMargins(0, 0, 0, bottomMargin);
        mChatBar.setLayoutParams(lp);
    }

    /**
     * 设置对战信息
     *
     * @param name
     */
    private void bindTargetInfo(String name, boolean visible) {
        NineteenApp.sHandler.post(new Runnable() {
            @Override
            public void run() {
                mTvTitle.setText(visible ? getString(R.string.game_running_format, name) : "");
                mChatBar.setVisibility(visible ? View.VISIBLE : View.GONE);
            }
        });
    }

    @JavascriptInterface
    public void postMessageToApp(final String data) {
        Logger.e("js调用Android->refreshOpponentName:" + data);
        GameCmdMsg cmdMsg = JSON.parseObject(data, GameCmdMsg.class);
        switch (cmdMsg.getCmd()) {
            case CMD_TARGET_JOIN:
                //成员加入
                mGameTargetJoin = JSON.parseObject(cmdMsg.getData(), GameTargetJoin.class);
                bindTargetInfo(mGameTargetJoin.getName(), true);
                onTargetJoin(mGameTargetJoin);
                break;
            case CMD_TARGET_LEAVE:
                //成员离开
                mGameTargetJoin = JSON.parseObject(cmdMsg.getData(), GameTargetJoin.class);
                bindTargetInfo(mGameTargetJoin.getName(), false);
                onTargetLeave(mGameTargetJoin);
                mGameTargetJoin = null;
                break;
            case CMD_USER_DETAIL:
                //用户详情
                GameUserInfo userInfo = JSON.parseObject(cmdMsg.getData(), GameUserInfo.class);
                loadUserInfo(userInfo.getUid());
                onUserInfo(userInfo);
                break;
            case CMD_RECHARGE:
                //充值
                RechargeActivity.launchActivity(this);
                break;
            case CMD_EXIT:
                //退出
                finish();
                break;
        }
    }

    /**
     * 加载用户详情
     *
     * @param uid
     */
    private void loadUserInfo(String uid) {
        convertUid2UserId(uid, new OnUid2UserIdResult() {
            @Override
            public void onConvert(String userId) {
                UserDetailActivity.launchNewTaskActivity(GameRunningTextActivity.this, userId);
            }
        });
    }

    /**
     * uid转换成userId
     *
     * @param uid
     * @param callback
     */
    protected void convertUid2UserId(String uid, OnUid2UserIdResult callback) {
        CDataProcessor.convertUserPkId2UserId(uid, new OkCallback<ConvertUidResponse>() {
            @Override
            public void onResponse(ConvertUidResponse response, String srcData) {
                if (response.isSuccess()) {
                    callback.onConvert(response.getObjId());
                } else {
                    Toasty.showNormal(response.getMessage());
                }
            }
        });
    }

    /**
     * 是否显示加载进度条
     *
     * @return
     */
    protected boolean useIndicatorEnable() {
        return true;
    }

    /**
     * 用户详情回调
     *
     * @param userInfo
     */
    protected void onUserInfo(GameUserInfo userInfo) {
    }

    /**
     * 目标离开回调
     *
     * @param targetLeave
     */
    protected void onTargetLeave(GameTargetJoin targetLeave) {
    }

    /**
     * 目标进入回调
     *
     * @param targetJoin
     */
    protected void onTargetJoin(GameTargetJoin targetJoin) {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(GameChatEvent event) {
        int duration = 3000 + 100 * event.chatText.length();
        if (event.isSend) {
            Logger.e("发送游戏聊天消息:" + event.chatText);
            mTxtSend.setText(event.chatText);
            AnimHelper.startGameMsgAnim(mTxtSend, duration, true, new Runnable() {
                @Override
                public void run() {
                    mTxtSend.setText("");
                    MessageQueueService.endMessageService(ApUtils.getApp());
                }
            });
        } else {
            Logger.e("接收游戏聊天消息:" + event.chatText);
            mTxtReceive.setText(event.chatText);
            AnimHelper.startGameMsgAnim(mTxtReceive, duration, false, new Runnable() {
                @Override
                public void run() {
                    mTxtReceive.setText("");
                    MessageQueueService.endMessageService(ApUtils.getApp());
                }
            });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(PaySuccessEvent event) {
        if (event != null) {
            initData();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().post(new FloatGameEvent(getClass(), false));
        MessageQueueService.stopMessageService(this);
        mAgentWeb.destroy();
    }

}
